home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 15424 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.8 KB  |  63 lines

  1. Path: news.th-darmstadt.de!news
  2. From: Enno Sandner <enno@intellektik.informatik.th-darmstadt.de>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: another overloading question
  5. Date: Thu, 04 Apr 1996 08:58:03 +0200
  6. Organization: Fachbereich Informatik, TH Darmstadt
  7. Message-ID: <316372FB.167EB0E7@intellektik.informatik.th-darmstadt.de>
  8. References: <4ju98d$3al@panoramix.fi.upm.es>
  9. NNTP-Posting-Host: kitz.intellektik.informatik.th-darmstadt.de
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.01 (X11; I; SunOS 4.1.3 sun4m)
  14.  
  15. Sacha wrote:
  16. > Hi,
  17. > Can I overload = for simple types?
  18. > I mean, if for example I have:
  19. >         class Colour
  20. >         {
  21. >         private:
  22. >           float r_, g_, b_;
  23. >         public:
  24. >           Colour(float r, float g, float b)
  25. >                 {r_=r; g_=g; b_=b;}
  26. >         };
  27. > is there some way I can overload = so that I can do things like:
  28. >         Colour colour(0.99238, 0.172364, 0.273);
  29. >         int intensity = colour;
  30. > such that intensity is assigned a value computed from r,g,b (e.g. the average)?
  31. > I think someone else may have asked this, phrasing it all with lvalues and
  32. > rvalues, but I lost the thread.
  33. > I suspect that the compiler treats simple types at compile time and there may be
  34. > no way to do this. I suppose I can substitute it with a normal member function...
  35.  
  36. You may provide a conversion operator that enables objects
  37. of class Colour to represent themselfs as integers, i.e.
  38.  
  39.         class Colour {
  40.                 ...
  41.                 public:
  42.                 ...
  43.                 operator int () const { return the_int_rep; }
  44.                 ...
  45.         };
  46.  
  47. An expression like 'int intensity=colour' will invoke
  48. the above conversion operator.
  49.  
  50.           Enno
  51.